Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
题目大意:给定一个矩阵,将0所在的行和列的所有元素智0,要求就地替换
题目难度:Medium
/**
* Created by gzdaijie on 16/5/30
* 复杂度O(N * M)
*/
public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length == 0) return;
if (matrix[0].length == 0) return;
int m = matrix.length;
int n = matrix[0].length;
// flag[0...m-1]标记行, flag[m...m + n - 1]标记列
boolean[] flag = new boolean[m + n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] != 0) continue;
flag[i] = flag[m + j] = true;
}
}
// 行置为0
for (int i = 0; i < m; i++) {
if (!flag[i]) continue;
for (int j = 0; j < n; j++) matrix[i][j] = 0;
}
// 列置为0
for (int i = 0; i < n; i++) {
if (!flag[m + i]) continue;
for (int j = 0; j < m; j++) matrix[j][i] = 0;
}
}
}